﻿using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.SharePoint;
using MS.InformationManagement.BLL.Helper;
using MS.InformationManagement.Core.RecordSiteQuery;
using MS.InformationManagement.Core.Support;
using MS.InformationManagement.DAL.DTOs;
using MS.InformationManagement.DAL.RecordCenter;
using MS.InformationManagement.Support;
using MS.InformationManagement.Support.Constants;
using Office = Microsoft.Office.DocumentManagement.DocumentSets;
using System.Text;
using MS.InformationManagement.DAL.DocumentCenter;

namespace MS.InformationManagement.BLL.ReasignarDocumento
{
    public class ReasignarDocumento
    {

        public List<UserDTO> GetUsersByDepartment()
        {
            //List<UserProfile> UsersByDepartment = PeopleHelper.GetUserListByProperty(GlobalConstants.UP_DEPARTMENT, PeopleHelper.GetPropertyCurrentUserProfile(GlobalConstants.UP_DEPARTMENT));
            return GetUsers();
        }

        private List<UserDTO> GetUsers()
        {
            string userSectionName = PeopleHelper.GetPropertyUserProfile(GlobalConstants.UP_DEPARTMENT, SPContext.Current.Web.CurrentUser.LoginName);
            List<UserDTO> users = RecursiveHelper.IsUserSectionAdmin(SPContext.Current.Web.CurrentUser.Name)
                ? GetUsersForAdminUser(userSectionName)
                : GetUsersForStandardUser(userSectionName);
            return users.OrderBy(user => user.DisplayName).ToList();
        }

        private List<UserDTO> GetUsersForAdminUser(string sectionName)
        {
            Seccion currentSection = GetUserSection(sectionName);
            Dictionary<string, string> result = PeopleHelper.GetUsersByProperty(GlobalConstants.UP_DEPARTMENT, sectionName, false);
            List<UserDTO> users = (from user in result select new UserDTO { LoginName = user.Key, DisplayName = user.Value }).ToList();
            RecursiveHelper.AddSectionAdminUsers(ref users, false);
            RecursiveHelper.AddSectionUsers(ref users, currentSection.Title);
            return users;
        }

        private List<UserDTO> GetUsersForStandardUser(string sectionName)
        {
            Seccion currentSection = GetUserSection(sectionName);
            Dictionary<string, string> result = PeopleHelper.GetUsersByProperty(GlobalConstants.UP_DEPARTMENT, sectionName, false);
            List<UserDTO> users = (from user in result select new UserDTO { LoginName = user.Key, DisplayName = user.Value }).ToList();
            string sectionOwnerName = currentSection.UsuarioEncargadoCorrespondencia;
            RecursiveHelper.AddSectionOwner(ref users, sectionOwnerName);
            return users;
        }

        private Seccion GetUserSection(string section)
        {
            string caml = String.Format("<Where><Eq><FieldRef Name='Title' /><Value Type='Text'>{0}</Value></Eq></Where>", section);
            Seccion userSection = QueryRecordsSiteHelper<Seccion>.QueryRecordsEntitiesSite(GlobalConstants.LIST_BIBLIOTECA_SECCION, caml, new Nullable<uint>()).FirstOrDefault();
            if (userSection == default(Seccion)) { throw new Exception(string.Format("La sección {0} no se encuentra", section)); }
            return userSection;
        }
        public string MoveRadicado(string listSourceID, string loginName, string itemsToMove)
        {
            StringBuilder mensaje = new StringBuilder();
            bool contieneRadicadosSalida = false;

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite ElevatedsiteColl = new SPSite(SPContext.Current.Site.ID))
                {
                    using (SPWeb ElevatedSite = ElevatedsiteColl.OpenWeb())
                    {
                        string userName = loginName.GetUserWithOutDomain().ToLower();
                        SPList ListaDestiny = ElevatedSite.Lists.TryGetList(userName);
                        SPList ListaSource = ElevatedSite.Lists[new Guid(listSourceID)];
                        Microsoft.Office.DocumentManagement.DocumentSets.DocumentSet dc = null;
                        Microsoft.Office.DocumentManagement.DocumentSets.DocumentSet movedElement;
                        SendEmailCommand emailCmd;

                        string[] ids = itemsToMove.Split('|');
                        for (int i = 0; i < (ids.Length - 1); i++)
                        {
                            dc = DocumentSetHelper.GetDocumentSet(ListaSource, int.Parse(ids[i]));

                            if (dc.ContentType.Name != GlobalConstants.CTTN_RADICADO_EMPRESA_SALIDA && dc.ContentType.Name != GlobalConstants.CTTN_RADICADO_PERSONA_SALIDA)
                            {
                                if (dc.ContentType.Name == GlobalConstants.CTTN_RADICADO_EMPRESA || dc.ContentType.Name == GlobalConstants.CTTN_RADICADO_PERSONA)
                                {
                                    if (dc.Folder.Item.Properties[CustomSiteColumns.FIELD_DOCSET_INTERNAL_RECEPTION] != null)
                                    {
                                        if (Convert.ToBoolean(dc.Folder.Item.Properties[CustomSiteColumns.FIELD_DOCSET_INTERNAL_RECEPTION]))
                                        {
                                            //moveChildsDocumentSet(dc.Folder.Item[CustomSiteColumns.FIELD_DOCSET_UNIQUE_ID].ToString(), ListaSource, ListaDestiny, userName);
                                            recursiveChild(DocumentSetHelper.getChildsFromDocumentSet(ListaSource, dc.Folder.Item[CustomSiteColumns.FIELD_DOCSET_UNIQUE_ID].ToString()), ListaDestiny, loginName);
                                            
                                            movedElement = MoveToLibrary(dc, ListaDestiny.RootFolder.Url, loginName);
                                            try
                                            {
                                                emailCmd = new SendEmailCommand(loginName, movedElement.Item, movedElement.Item.ID, movedElement.ParentList.ID.ToString()
                                                                                        , movedElement.Item.ContentType.Name, true, ElevatedSite);
                                                emailCmd.Execute();
                                            }
                                            catch (Exception)
                                            {
                                            }
                                            mensaje.Append(string.Format(GlobalConstants.SUCCESS_MOVETO_RADICADO + " <br />", dc.Folder.Item.Properties[CustomSiteColumns.FIELD_DOCSET_UNIQUE_ID]));
                                            //TODO: Eliminar el try catch cuando se implemente el patron de transacciones
                                            
                                            
                                        }
                                        else
                                            mensaje.Append(string.Format(GlobalConstants.FAIL_MOVETO_RADICADO_DISTRIBUCION + " <br />", dc.Folder.Item.Properties[CustomSiteColumns.FIELD_DOCSET_UNIQUE_ID]));
                                    }
                                    else
                                        mensaje.Append(string.Format(GlobalConstants.FAIL_MOVETO_RADICADO_DISTRIBUCION + " <br />", dc.Folder.Item.Properties[CustomSiteColumns.FIELD_DOCSET_UNIQUE_ID]));
                                }
                                else
                                {
                                    //moveChildsDocumentSet(dc.Folder.Item[CustomSiteColumns.FIELD_DOCSET_UNIQUE_ID].ToString(), ListaSource, ListaDestiny, userName);
                                    recursiveChild(DocumentSetHelper.getChildsFromDocumentSet(ListaSource, dc.Folder.Item[CustomSiteColumns.FIELD_DOCSET_UNIQUE_ID].ToString()), ListaDestiny, loginName);
                                    
                                    movedElement = MoveToLibrary(dc, ListaDestiny.RootFolder.Url, loginName);
                                    //TODO: Eliminar el try catch cuando se implemente el patron de transacciones
                                    try
                                    {
                                        emailCmd = new SendEmailCommand(loginName, movedElement.Item, movedElement.Item.ID, movedElement.ParentList.ID.ToString()
                                                                                        , movedElement.Item.ContentType.Name, true, ElevatedSite);
                                        emailCmd.Execute();
                                    }
                                    catch (Exception)
                                    {


                                    }
                                    
                                    mensaje.Append(string.Format(GlobalConstants.SUCCESS_MOVETO_RADICADO + " <br />", dc.Folder.Item.Properties[CustomSiteColumns.FIELD_DOCSET_UNIQUE_ID]));
                                }
                            }
                            else
                            {
                                contieneRadicadosSalida = true;
                            }

                        }
                        if (contieneRadicadosSalida == true)
                        {
                            mensaje.Append(GlobalConstants.FAIL_MOVETO_RADICADO_SALIDA + " <br />");
                        }
                    }
                }
            });



            return mensaje.ToString();
        }

        public bool MoveRadicadoAnulado(Office.DocumentSet itemToMove, SPList ListaDestiny, string LoginName)
        {
            bool result = false;
            Microsoft.Office.DocumentManagement.DocumentSets.DocumentSet dc = itemToMove;
            MoveToLibrary(dc, ListaDestiny.RootFolder.Url, LoginName);
            result = true;

            return result;
        }

        private Microsoft.Office.DocumentManagement.DocumentSets.DocumentSet MoveToLibrary(Microsoft.Office.DocumentManagement.DocumentSets.DocumentSet currentDocumentSet, string FolderUrl, string userName)
        {
            Microsoft.Office.DocumentManagement.DocumentSets.DocumentSet newDocumentSet = null;
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                SPUserToken systoken = SPContext.Current.Site.SystemAccount.UserToken;
                using (SPSite currentSite = new SPSite(SPContext.Current.Web.Url, systoken))
                {
                    using (SPWeb currentWeb = currentSite.OpenWeb())
                    {
                        SPUser currentUser = currentWeb.EnsureUser(userName);
                        currentDocumentSet.ParentList.ParentWeb.AllowUnsafeUpdates = true;
                        currentWeb.AllowUnsafeUpdates = true;
                        currentDocumentSet.Folder.Item.Update();
                        SPContentType ctoriginal = currentDocumentSet.ContentType;
                        string Descripcion = currentDocumentSet.Folder.Item[CustomSiteColumns.FIELD_CURRENT_ACTION] + "";
                        string uniqueID = currentDocumentSet.Folder.Item[CustomSiteColumns.FIELD_DOCSET_UNIQUE_ID] + "";
                        FolderUrl = FolderUrl + @"\" + uniqueID;
                        currentDocumentSet.Folder.Item[CustomSiteColumns.FIELD_CURRENT_ACTION] = "MoveTo";
                        currentDocumentSet.Folder.Item.Update();
                        currentDocumentSet.Folder.MoveTo(FolderUrl);

                        SPFolder newFolder = currentWeb.GetFolder(FolderUrl);
                         newDocumentSet = Microsoft.Office.DocumentManagement.DocumentSets.DocumentSet.GetDocumentSet(newFolder);
                        newDocumentSet.Folder.Item.Update();
                        newDocumentSet.Folder.Item[CustomSiteColumns.FIELD_CURRENT_ACTION] = Descripcion;
                        newDocumentSet.Folder.Item[SPBuiltInFieldId.ContentTypeId] = ctoriginal.Id;
                        newDocumentSet.Folder.Item[CustomSiteColumns.FIELD_EXPEDIENTE_ASSIGNED] = currentUser;
                        newDocumentSet.Log(string.Empty, DateTime.Now, Support.Enums.TraceableOperation.Reasignado
                            , currentUser.Name, string.Format("Documento reasignado a {0}", PeopleHelper.GetUserByLoginName(userName).User.Name));
                        newDocumentSet.Folder.Item.Update();
                        currentWeb.AllowUnsafeUpdates = false;
                        currentDocumentSet.ParentList.ParentWeb.AllowUnsafeUpdates = false;
                    }
                }
            });
            return newDocumentSet;
        }

        public string contieneSalida(string listSourceID, string itemsToMove)
        {
            string mensaje = string.Empty;
            SPList ListaSource = SPContext.Current.Web.Lists[new Guid(listSourceID)];
            string[] ids = itemsToMove.Split('|');
            for (int i = 0; i < (ids.Length - 1); i++)
            {
                SPListItem item = ListaSource.GetItemById(int.Parse(ids[i]));
                if (item.ContentType.Name == GlobalConstants.CTTN_RADICADO_EMPRESA_SALIDA || item.ContentType.Name == GlobalConstants.CTTN_RADICADO_PERSONA_SALIDA)
                {
                    mensaje += "";
                }
            }
            return mensaje;
        }

        private void recursiveChild(SPListItemCollection documents, SPList ListaDestiny, string userName)
        {
            if (documents != null)
            {
                foreach (SPListItem item in documents)
                {
                    Microsoft.Office.DocumentManagement.DocumentSets.DocumentSet dc = null;
                    dc = DocumentSetHelper.GetDocumentSet(item.ParentList, item.ID);
                    MoveToLibrary(dc, ListaDestiny.RootFolder.Url, userName);
                    SPListItemCollection itemsChild = DocumentSetHelper.getChildsFromDocumentSet(item.ParentList, item[CustomSiteColumns.FIELD_DOCSET_UNIQUE_ID].ToString());
                    if (itemsChild != null)
                    {
                        recursiveChild(itemsChild, ListaDestiny, userName);
                    }
                }
            }
        }

    }
}
